﻿using System;
using System.Web.UI;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using System.Collections.Generic;
using Evolution.Utilities;

namespace Evolution.UI.WebParts
{
    [Serializable]
    public class ManageWebPartsAction : BaseAction
    {
        #region Constructors

        public ManageWebPartsAction()
        {

        }

        public ManageWebPartsAction(ManagedWebPart[] webParts)
        {
            this.WebParts = webParts;
        }

        #endregion

        #region Properties

        public ManagedWebPart[] WebParts { get; set; }

        public override string Caption
        {
            get { return "Manage Web Parts"; }
        }

        #endregion

        #region Methods

        public override void CreateInterface(ControlCollectionBuilder builder, PageActionEditor editor)
        {
            HiddenField webPartListHidden = new HiddenField();
            webPartListHidden.ID = "Evolution_Pawp_WebPartListHidden";
            webPartListHidden.Value = "";
            builder.AddControl(webPartListHidden);

            builder.AddStaticText(@"
                    <br/><div class=""UserSectionBody"" style=""margin-top: 5px;"">To specify which Web Parts show or hide, click <B>Select Web Parts</B>. 
                        <div class=""UserControlGroup"" style=""PADDING-TOP: 5px"">
                            <input class=""UserButton"" id=""INPUTSelectWebParts"" style=""WIDTH: 165px"" onclick=""javascript:showModalDialog('{0}', [ document.getElementById('{1}'), Evolution_Pawp_WebPartsArray ],'dialogHeight:340px;dialogWidth:450px;help:no;status:no;resizable:no');"" type=""button"" value=""Select Web Parts..."" />
                        </div>
                    </div>", SPContext.Current.Site.Url + "/_layouts/Evolution/code/WebPartsManagementDialogBox.htm", webPartListHidden.ClientID);

            builder.AddErrorPlaceholder("WebPartsList");

            SPWebPartManager manager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(editor.Page);
            if (manager == null)
                throw new InvalidOperationException("The SPWebPartManager returned from GetCurrentWebPartManager method is null.");

            string webPartArray = String.Empty;
            foreach (System.Web.UI.WebControls.WebParts.WebPart part in manager.WebParts)
                if ((part as PageActionWebPart) == null)
                    webPartArray += "[ \"" + part.ID + "\", \"" + part.Title + "\" ], ";

            if (webPartArray != String.Empty)
                webPartArray = webPartArray.Substring(0, webPartArray.Length - 2);

            editor.Page.ClientScript.RegisterArrayDeclaration("Evolution_Pawp_WebPartsArray", webPartArray);
        }

        public override void Execute(Page page, PageActionWebPart part)
        {
            SPWebPartManager manager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(page);
            if (manager == null)
                throw new InvalidOperationException("The SPWebPartManager returned from GetCurrentWebPartManager method is null.");

            ManagedWebPart[] webParts = this.WebParts;
            foreach (ManagedWebPart webPart in webParts)
            {
                string id = webPart.ID;
                System.Web.UI.WebControls.WebParts.WebPart wp = manager.WebParts[id];
                if (wp != null)
                    wp.Hidden = webPart.Hidden;
                else
                    throw new InvalidOperationException(String.Format("The specified Web Part does not belong the collection of Web Parts on this page. Web Part ID = '{0}'.", id));
            }
        }

        public override bool IsValidAction(PageActionWebPart part, out string errorMessage)
        {
            errorMessage = String.Empty;

            SPWebPartManager manager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(part.Page);
            
            if (manager == null)
                errorMessage = "The SPWebPartManager returned from GetCurrentWebPartManager method is null.";
            else
            {                
                ManagedWebPart[] webParts = this.WebParts;
                foreach (ManagedWebPart webPart in webParts)
                {
                    string id = webPart.ID;
                    System.Web.UI.WebControls.WebParts.WebPart wp = manager.WebParts[id];
                    if (wp == null)
                        errorMessage = (String.IsNullOrEmpty(errorMessage) ? "" : errorMessage + "<br/>") + String.Format("The specified Web Part does not belong the collection of Web Parts on this page. Web Part ID = '{0}'.", id);
                }
            }
            return String.IsNullOrEmpty(errorMessage);
        }

        public override string GetDescription()
        {
            return "Manage Web Parts";
        }

        public override void ApplyChanges(PageActionEditor editor)
        {
            HiddenField hiddenField = editor.FindControl("Evolution_Pawp_WebPartListHidden") as HiddenField;
            if (!StringUtility.IsNullOrEmpty(hiddenField.Value))
            {
                string[] text = hiddenField.Value.Substring(1, hiddenField.Value.Length - 2).Split(new char[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

                List<ManagedWebPart> webParts2 = new List<ManagedWebPart>();
                for (int i = 0; i < text.Length; )
                    webParts2.Add(new ManagedWebPart(text[i++].Trim(), Convert.ToInt32(text[i++]) == 0));

                this.WebParts = webParts2.ToArray();
            }
            else
                editor.RaiseError("WebPartsList", "Specify at least one Web Part to display or hide.", String.Format("The action '{0}' requires the indication of at least one Web Part to display or hide.", this.Caption));            
        }

        public override void SyncChanges(PageActionEditor editor)
        {
            HiddenField hiddenField = editor.FindControl("Evolution_Pawp_WebPartListHidden") as HiddenField;
            ManagedWebPart[] webParts = this.WebParts;

            string text = String.Empty;
            foreach (ManagedWebPart wps in webParts)
                text += wps.ID + " : " + (wps.Hidden ? 0 : 1) + ", ";

            if (!String.IsNullOrEmpty(text))
                hiddenField.Value = "{ " + text.Substring(0, text.Length - 2) + " }";
        }

        #endregion
    }
}
